//
//  MessageViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/2/27.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "MessageViewController.h"
#import <SMS_SDK/SMSSDK.h>
#import "MyselfViewController.h"
#import "SetBlack.h"
#import "BlackManager.h"
@interface MessageViewController ()<UITextFieldDelegate>//输入框协议
@property (nonatomic, retain)UITextField *phoneInput;
@property (nonatomic, retain)UITextField *checkInput;
@property (nonatomic, retain)UITextField *pwdInput;
@property (nonatomic, retain)UIButton *getNumBtn;//获取验证码按钮
@end

@implementation MessageViewController
-(void)dealloc
{
    [_phoneInput release];
    [_checkInput release];
    [_pwdInput release];
    [_getNumBtn release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"短信注册";
    //手机号输入框
    self.phoneInput = [[UITextField alloc]initWithFrame:CGRectMake(10, self.view.frame.size.height / 6, self.view.frame.size.width - 20, self.view.frame.size.height / 14)];
    _phoneInput.delegate = self;
    _phoneInput.tag = 1000;
    _phoneInput.layer.cornerRadius = 10;
    _phoneInput.clipsToBounds = YES;
    _phoneInput.placeholder = @"请输入手机号";
    _phoneInput.backgroundColor = [UIColor lightGrayColor];
    _phoneInput.clearButtonMode = UITextFieldViewModeAlways;//只要开始输入就有删除的叉号
    [self.view addSubview:_phoneInput];
    [_phoneInput release];
    //验证码输入框
    self.checkInput = [[UITextField alloc]initWithFrame:CGRectMake(10, _phoneInput.frame.origin.y + _phoneInput.frame.size.height + 10, (self.view.frame.size.width - 20) / 3 * 2, self.view.frame.size.height / 14)];
    _checkInput.tag = 2000;
    _checkInput.delegate = self;
    _checkInput.layer.cornerRadius = 10;
    _checkInput.clipsToBounds = YES;
    _checkInput.placeholder = @"请输入验证码";
    _checkInput.backgroundColor = [UIColor lightGrayColor];
    _checkInput.clearButtonMode = UITextFieldViewModeAlways;//只要开始输入就有删除的叉号
    [self.view addSubview:_checkInput];
    [_checkInput release];
    //获取验证码按钮
    UIButton *getNumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    getNumBtn.frame = CGRectMake(_checkInput.frame.origin.x + _checkInput.frame.size.width + 2, _checkInput.frame.origin.y, _checkInput.frame.size.width / 2, _checkInput.frame.size.height);
    getNumBtn.layer.cornerRadius = 10;
    getNumBtn.clipsToBounds = YES;
    [getNumBtn setBackgroundColor:[UIColor redColor]];
    [getNumBtn setTintColor:[UIColor grayColor]];
    [getNumBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [getNumBtn addTarget:self action:@selector(getNumAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:getNumBtn];
    
    //密码输入框
    self.pwdInput = [[UITextField alloc]initWithFrame:CGRectMake(10, _checkInput.frame.origin.y + _checkInput.frame.size.height + 10, _phoneInput.frame.size.width, self.view.frame.size.height / 14)];
    _pwdInput.tag = 3000;
    _pwdInput.delegate = self;
    _pwdInput.layer.cornerRadius = 10;
    _pwdInput.clipsToBounds = YES;
    _pwdInput.secureTextEntry = YES;
    _pwdInput.placeholder = @"请输入密码";
    _pwdInput.backgroundColor = [UIColor lightGrayColor];
    _pwdInput.clearButtonMode = UITextFieldViewModeAlways;//只要开始输入就有删除的叉号
    [self.view addSubview:_pwdInput];
    [_pwdInput release];
    //下一步按钮
    //手机发短信
    UIButton *nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(self.view.frame.size.width / 5, _pwdInput.frame.origin.y + _pwdInput.frame.size.height + 100, self.view.frame.size.width / 5 * 3, self.view.frame.size.height / 14);
    [nextBtn addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    nextBtn.layer.cornerRadius = 10;
    nextBtn.clipsToBounds = YES;
    [nextBtn setBackgroundColor:[UIColor redColor]];
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [self.view addSubview:nextBtn];
    
    
}
#pragma mark - 夜间模式设置
//设置夜间模式  重写BaseViewController中的方法
-(void)setNightDayModel
{
    [SetBlack setBackgroundColorWithView:self.view];
}
-(void)setLightDayModel
{
    [SetBlack setBackgroundColorWithView:self.view];
    
}
#pragma mark - 点击屏幕收起键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
#pragma mark - 回收键盘
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    if (textField.tag == 1000) {
        [textField resignFirstResponder];
        [_checkInput becomeFirstResponder];
    }else if (textField.tag == 2000) {
        [textField resignFirstResponder];
        [_pwdInput becomeFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return YES;
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField.tag == 3000) {
        self.view.center = CGPointMake(self.view.center.x, self.view.center.y - 50);
    }
    return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag == 3000) {
        self.view.center = CGPointMake(self.view.center.x, self.view.center.y + 50);
    }
}
#pragma mark - 获取验证码方法
//获取验证码
-(void)getNumAction
{
    //判断手机号是否注册过
    //从本地路径中解档数据
    NSString *namePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"name.a"];
    NSMutableArray *nameArr = [NSKeyedUnarchiver unarchiveObjectWithFile:namePath];
    //判断账户是否存在
    if ([nameArr containsObject:_phoneInput.text]) {
        
        UIAlertController *jumpAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"手机号已经被注册过" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:jumpAlert animated:YES completion:^{
            
        }];
        [self dismissViewControllerAnimated:YES completion:^{
            //
        }];
    }else{
        //发送验证码
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_phoneInput.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
            //
            if (!error) {
                NSLog(@"获取验证码成功");
                [_getNumBtn setTitle:@"获取成功" forState:UIControlStateNormal];
                //提示弹窗
                UIAlertController *yesAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"获取验证码成功" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:yesAlert animated:YES completion:^{
                    
                }];
                [self dismissViewControllerAnimated:YES completion:^{
                    //
                }];
            } else {
                NSLog(@"错误信息：%@",error);
                //提示弹窗
                UIAlertController *noAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"获取验证码失败" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:noAlert animated:YES completion:^{
                    
                }];
                [self dismissViewControllerAnimated:YES completion:^{
                    //
                }];
            };
        }];
    }

    
}
#pragma mark - 核对验证码进行下一步方法
-(void)nextAction
{
    //判断是否有验证码
    if (_pwdInput.text.length != 0) {
        [SMSSDK commitVerificationCode:_checkInput.text phoneNumber:_phoneInput.text zone:@"86" result:^(NSError *error) {
            //
            if (!error) {
                NSLog(@"验证成功");
                //用手机号注册
                [self registerAction];
                MyselfViewController *myVC = [[MyselfViewController alloc]init];
                [self.navigationController popToViewController:myVC animated:YES];
                [myVC release];
            }
            else
            {
                NSLog(@"错误信息:%@",error);
                //提示弹窗
                UIAlertController *noAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"验证码验证错误" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:noAlert animated:YES completion:^{
                    
                }];
                [self dismissViewControllerAnimated:YES completion:^{
                    //
                }];

            }
        }];

    }else{
        //提示弹窗
        UIAlertController *nopwdAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入密码" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:nopwdAlert animated:YES completion:^{
            
        }];
        [self dismissViewControllerAnimated:YES completion:^{
            //
        }];

    }
    
}
#pragma mark - 核对信息后用手机号注册
-(void)registerAction
{
    if (_phoneInput.text.length != 0 && _pwdInput.text.length != 0 ) {
        //把姓名写在单例里
        [[NSUserDefaults standardUserDefaults]setObject:_phoneInput.text forKey:@"name"];
        //弹窗
        UIAlertController *promptAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"注册成功" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:promptAlert animated:YES completion:^{
            
        }];
#pragma mark - 存储数据
        //在Caches中创建文件储存用户的姓名和密码
        //存储姓名
        NSString *namePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"name.a"];
        //从namepath路径解档获取数组
        NSMutableArray *nameArr = [NSKeyedUnarchiver unarchiveObjectWithFile:namePath];
        if (nameArr) {
            [nameArr addObject:_phoneInput.text];
        }else{
            nameArr = [NSMutableArray array];
            [nameArr addObject:_phoneInput.text];
        }
        
        //将数组归档
        [NSKeyedArchiver archiveRootObject:nameArr toFile:namePath];
        //存储密码
        NSString *pwdPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"pwd.a"];
        NSMutableArray *pwdArr = [NSKeyedUnarchiver unarchiveObjectWithFile:pwdPath];
        if (pwdArr) {
            [pwdArr addObject:_pwdInput.text];
        }else{
            pwdArr = [NSMutableArray array];
            [pwdArr addObject:_pwdInput.text];
        }
        //密码归档
        [NSKeyedArchiver archiveRootObject:pwdArr toFile:pwdPath];
        //储存照片
        //存储照片的本地路径
        NSString *picturePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"picture.a"];
        NSMutableArray *pictureArr = [NSKeyedUnarchiver unarchiveObjectWithFile:picturePath];
        if (pictureArr) {
            [pictureArr addObject:@"1"];
        }else{
            pictureArr = [NSMutableArray array];
            [pictureArr addObject:@"1"];
        }
        //图片归档
        [NSKeyedArchiver archiveRootObject:pictureArr toFile:picturePath];
        
        //存储新创建用户的位置(NSNumber型存放)
        NSNumber *indexNum = @(pictureArr.count - 1);
        [[NSUserDefaults standardUserDefaults]setObject:indexNum forKey:@"index"];
        
        //NSUserDefaults 设置登陆成功状态
        NSLog(@"%@", NSHomeDirectory());
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"register"];
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"OtherLogin"];
        //让弹窗消失
        [self dismissViewControllerAnimated:YES completion:^{
            //
            [self.navigationController popToRootViewControllerAnimated:YES];
            NSLog(@"注册成功");
        }];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
